package study.wechat.pub.client;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import study.eggs.utils.JsonUtils;

import javax.annotation.PostConstruct;
import java.util.Map;

@Slf4j
@Component
public class WechatHttp {

    private static String HOST = "https://api.weixin.qq.com";

    private static RestTemplate CLIENT;

    @Autowired
    private RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        CLIENT = restTemplate;
    }

    public static String get(String path, Map<String, Object> param) {
        log.info("[{}] i: {}", path, JsonUtils.toJson(param));
        // url
        String query = MapUtil.join(param, "&", "=");
        String url = StrUtil.builder(HOST, path, "?", query).toString();
        // request
        String body;
        try {
            body = CLIENT.getForObject(url, String.class);
        } catch (Exception ex) {
            throw new RuntimeException(StrUtil.format("请求[{}]错误: ", path), ex);
        }
        log.info("[{}] o: {}", path, body);
        return body;
    }

    public static String post(String path, String body, Map<String, Object> querys) {
        log.info("[{}] i: {}", path, body);
        // url
        String url;
        if (MapUtil.isNotEmpty(querys)) {
            String query = MapUtil.join(querys, "&", "=");
            url = StrUtil.builder(HOST, path, "?", query).toString();
        } else {
            url = StrUtil.builder(HOST, path).toString();
        }
        // request
        String resp;
        try {
            // header
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            // entity
            HttpEntity<String> request = new HttpEntity(body, headers);
            //
            resp = CLIENT.postForObject(url, request, String.class);
        } catch (Exception ex) {
            throw new RuntimeException(StrUtil.format("请求[{}]错误: ", path), ex);
        }
        log.info("[{}] o: {}", path, resp);
        return resp;
    }
}
